#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>

int log_enable = 0;
int log_to_file = 0;

#define LOG_FILE "/var/oneagent_mon_log.txt"

void log_mon(const char *format, ...)
{
	FILE *logfd = NULL;
	va_list args;

	if (log_enable){
		if (log_to_file){
			logfd = fopen(LOG_FILE, "a");
			if(logfd){
				fprintf(logfd, format, args);
				fprintf(logfd, "%s", "\n");
				fflush(logfd);
				fclose(logfd);
			}
		}
		else{
			fprintf(stdout, format, args);
			fprintf(stdout,"%s","\n");
			fflush(stdout);
		}
	}
}

void restart_oneagent()
{
	//log_mon("----- implement oneagent restart function here -----");
	system("/etc/init.d/tr-069 restart &");
}

void sigusr1_handler()
{
	log_mon("----- recv SIGUSR1, restart oneagent now -----");
	restart_oneagent();
}

void sigusr2_handler()
{
	log_mon("----- recv SIGUSR2, no action defined, do nothing -----");
}

void sigalrm_handler()
{
	log_mon("----- recv SIGALRM, no action defined, do nothing -----");
}

void sigterm_handler()
{
	log_mon("----- recv SIGTERM, exit now -----");
	_exit(EXIT_SUCCESS);
}

void init_signal_handler()
{
	signal(SIGUSR1, sigusr1_handler);
	signal(SIGUSR2, sigusr2_handler);
	signal(SIGALRM, sigalrm_handler);
	signal(SIGTERM, sigterm_handler);
}

void display_usage(char *s)
{
	fprintf(stderr, "\n");
	fprintf(stderr, "Usage: %s [-lf]\n", s);
	fprintf(stderr, "      -l, enable debug, print log to stdout by default\n");
	fprintf(stderr, "      -f, used with option l, print log to file, /var/oneagent_mon_log.txt\n");
	fprintf(stderr, "Signals:\n");
	fprintf(stderr, "      USR1	Restart oneagent\n");
	fprintf(stderr, "      USR2	To be defined\n");
	fprintf(stderr, "\n");
	fflush(stderr);
	exit(EXIT_FAILURE);
}

void parse_args(int argc, char **argv)
{
	int opt;

	while((opt = getopt(argc, argv, "lfh")) != -1){
		switch (opt) {
			case 'l':
				log_enable = 1;
				break;
			case 'f':
				log_to_file = 1;
				break;
			case 'h':
				display_usage(argv[0]);
				break;
			default :
				display_usage(argv[0]);
				break;
		}
	}	
	log_mon("log_enable=%d, log_to_file=%d\n", log_enable, log_to_file);
}

void main(int argc, char *argv[])
{
	parse_args(argc, argv);
	daemon(0, log_enable);
	init_signal_handler();

	while(1)
	{
		pause();
	}
}

